<template>
    <div class="plantBox">
        <div style="width: 100%;height: 40%;display: flex;">
            <div class="title"> <span>各个果园占地面积</span> <span v-if="plantInfo.name">{{ plantInfo.name }}各个品种占地面积</span></div>
            <div class="plant-left" ref="plantLeft"></div>
            <div class="plant-right" ref="plantRight"></div>
            <dv-loading v-if="loadings"
                style="width: 80px;height: 100px;color: #fff;position: absolute;top: 60px;right: 280px;">加载中...</dv-loading>
        </div>
        <div style="width: 100%;height: 60%;">
            <div ref="plantBottom" style="width: 98%;height:98%;"></div>
        </div>
    </div>
</template>
<script>
import * as echarts from "echarts";
export default {
    props: ['typeValue'],
    data() {
        return {
            tableData: [],
            loadings: false,
            //种植参数
            plantInfo: {
                name: "",
                type: ""
            },
        }
    },
    mounted() {
        this.getplanteCharts()
    },
    watch: {
        typeValue: {
            handler(newValue) {
                this.plantInfo.name = newValue.name;
                this.plantInfo.type = newValue.type;
                this.getplanteCharts();
            },
            deep: true
        }
    },
    methods: {
        // 种植弹窗echart
        async getplanteCharts() {
            let { data: res } = await this.$https('plant/iot/getPlant?type=' + this.plantInfo.type)
            // console.log(res)
            if (res.code != 200) return
            let datas = res.data.map(v => {
                return {
                    name: v.name,
                    value: Number(v.area),
                    prod: Number(v.prod)
                }
            })
            let myChartL = echarts.getInstanceByDom(this.$refs.plantLeft);
            if (myChartL == undefined) {
                myChartL = echarts.init(this.$refs.plantLeft);
            }
            let myChartB = echarts.getInstanceByDom(this.$refs.plantBottom);
            if (myChartB == undefined) {
                myChartB = echarts.init(this.$refs.plantBottom);
            }
            let plantName = datas.map(v => { return v.name })
            let prodData = datas.map(v => { return v.prod })
            const colorData = [
                {
                    c1: '#BCC755',
                    c2: '#B0BE4B',
                },
                {
                    c1: '#FF9A27',
                    c2: '#FFC44F',
                },
                {
                    c1: '#FFE74A',
                    c2: '#FFEA4E',
                },
                {
                    c1: '#30D96A',
                    c2: '#5DE9A6',
                },
                {
                    c1: '#4585FF',
                    c2: '#5EB7FF',
                },
                {
                    c1: '#562EFF',
                    c2: '#A062FF',
                },
                {
                    c1: '#D1A8F6',
                    c2: '#C098EC',
                },
                {
                    c1: '#6DCFFF',
                    c2: '#96DDFF',
                },
                {
                    c1: '#30D96A',
                    c2: '#5DE9A6',
                },
                {
                    c1: '#4585FF',
                    c2: '#5EB7FF',
                },
            ];
            let optionL = {
                backgroundColor: '',
                grid: {
                    left: 500,
                    top: 180,
                    bottom: 10,
                    right: 10,
                    containLabel: true,
                },
                polar: {},
                angleAxis: {
                    interval: 1,
                    type: 'category',
                    data: [],
                    z: 10,
                    axisLine: {
                        show: false,
                    },
                    axisLabel: {
                        show: false,
                    },
                },
                radiusAxis: {
                    min: 40,
                    max: 120,
                    interval: 20,
                    axisLine: {
                        show: false
                    },
                    axisLabel: {
                        show: false,
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(73, 151, 195, 1)',
                            width: 1,
                            type: 'solid',
                        },
                    },
                },
                calculable: true,
                series: [
                    // 内背景
                    {
                        type: 'pie',
                        center: ['50%', '50%'],
                        radius: [0, '80%'],
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        itemStyle: {
                            color: '#022654'
                        },
                        silent: true,
                        data: [
                            {
                                value: 100,
                                name: ''
                            }
                        ]
                    },
                    // 外圈
                    {
                        // 外层刻度
                        name: "",
                        type: 'gauge',
                        splitNumber: 240, // 刻度数量
                        radius: '95%', // 图表尺寸
                        center: ['50%', '50%'],
                        startAngle: 90,
                        endAngle: -269.9999,
                        axisLine: {
                            show: false,
                            lineStyle: {
                                width: 0,
                                shadowBlur: 0,
                                color: [
                                    [1, 'rgba(54, 255, 205, .1)']
                                ]
                            }
                        },
                        axisTick: {
                            show: false,
                            lineStyle: {
                                color: 'auto',
                                width: 1
                            },
                            length: 100,
                            splitNumber: 1
                        },
                        splitLine: {
                            show: true,
                            length: 2,
                            lineStyle: {
                                color: 'auto',
                            }
                        },
                        axisLabel: {
                            show: false
                        }
                    },
                    {
                        type: 'pie',
                        radius: ['20%', '80%'],
                        backgroundColor: '#fff',
                        roseType: 'area',
                        zlevel: 10,
                        label: {
                            show: true,
                            formatter: function (param) {
                                return [`{a|${param.name}}` + '\n' + `{b|${(param.value*10000).toFixed(0)}亩}`];
                            },
                            rich: {
                                a: {
                                    fontSize: '13',
                                },
                                b: {
                                    fontSize: 14,
                                },
                            },
                            position: 'outside',
                        },
                        itemStyle: {
                            color: function (params) {
                                return new echarts.graphic.LinearGradient(0.5, 0, 0.5, 1, [
                                    {
                                        offset: 0,
                                        color: colorData[params.dataIndex].c1,
                                    },
                                    {
                                        offset: 1,
                                        color: colorData[params.dataIndex].c2,
                                    },
                                ]);
                            },
                            shadowColor: function (params) {
                                return "rgba(0, 0, 0, 0.8)"
                            },
                            shadowBlur: 50,
                        },
                        labelLine: {
                            show: true,
                            length: 10,
                            length2: 20,
                            color: '#4BCFFC'
                        },
                        data: datas.map((item, index) => {
                            return {
                                ...item,
                                label: {
                                    color: colorData[index].c2
                                }
                            }
                        }),
                    },
                ],
            };

            let optionB = {
                backgroundColor: '',
                color: "#c0c3cd",
                fontSize: 14,
                grid: {
                    top: '23%',
                    left: '5%',
                    bottom: '10%',
                    right: '5%'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function (params) {
                        return params[0].name + ' : ' + params[0].data + '万吨';
                    }
                },
                xAxis: {
                    nameTextStyle: {
                        "color": "#c0c3cd",
                        "padding": [0, 0, -10, 0],
                        "fontSize": 14
                    },
                    axisLabel: {
                        interval: 0,
                        color: '#639FD2', //坐标轴字颜色
                        margin: 15
                    },
                    axisTick: {
                        show: false //隐藏X轴刻度
                    },
                    splitLine: {     //网格线
                        "show": false
                    },
                    data: plantName,
                    type: "category"
                },
                yAxis: {
                    name: '果园总产量(万吨)',
                    axisLine: {
                        show: false, //隐藏X轴轴线
                    },
                    axisTick: {
                        show: false //隐藏X轴刻度
                    },
                    axisLabel: {
                        color: '#fff'
                    },
                    splitLine: {     //网格线
                        show: false
                    }
                },
                series: [
                    {
                        name: '',
                        data: prodData,
                        type: "bar",
                        showBackground: false,
                        barMaxWidth: "auto",
                        symbolSize: 0,
                        barWidth: 17,
                        itemStyle: {
                            //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                            color: function (params) {
                                var colorList = ['#027db4', '#03b915', '#ffe400', '#bd4fff', '#8be68e', '#dce19d', '#62edf8', '#0676A7'];
                                return colorList[params.dataIndex];
                            },
                        },
                        label: {
                            "show": true,
                            "position": "top",
                            "distance": 10,
                            "color": "#fff",
                            "fontSize": 13
                        }
                    },
                ],
            };
            myChartL.setOption(optionL)
            myChartL.on('click', (param) => {
                if (this.plantInfo.name == param.name) return
                this.setBing(param.name)
            })
            myChartB.setOption(optionB)
        },
        //种植品种生成右边饼图
        async setBing(name) {
            this.plantInfo.name = name
            this.loadings = true
            let myChartR = echarts.getInstanceByDom(this.$refs.plantRight);
            if (myChartR == undefined) {
                myChartR = echarts.init(this.$refs.plantRight);
            }
            myChartR.clear()
            let { data: res } = await this.$https('plant/iot/getPlantInfo', { params: this.plantInfo })
            console.log(res)
            if (res.code != 200) return 
            this.loadings = false
            if(res.data.length<=0)return this.showNone = true
            const colorList = ["rgba(67,106,218,0.45)", "rgba(217,95,95,0.45)", "rgba(205,217,101,0.45)", "rgba(233,174,90,0.45)", "rgba(135,208,81,0.45)", "rgba(48,154,227,0.75)"]
            const optionsData = res.data.map((v, i) => {
                return {
                    name: v.name,
                    value: v.area,
                    itemStyle: {
                        color: colorList[i]
                    }
                }
            })


            const series = this.getPie3D(
                optionsData,
                0
            );
            // 准备待返回的配置项，把准备好的 legendData、series 传入。
            series.push({
                name: "pie2d",
                type: "pie",
                label: {
                    opacity: 1,
                    fontSize: 14,
                    lineHeight: 20,
                    fontSize: 14,
                    color: "#fff",
                },
                labelLine: {
                    length: 30,
                    length2: 30,
                },
                startAngle: -30, //起始角度，支持范围[0, 360]。
                clockwise: false, //饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式
                radius: ["50%", "50%"],
                center: ["50%", "50%"],
                data: optionsData,
                itemStyle: {
                    opacity: 0,
                },
            });
            let optionR = {
                legend: {
                    show: false,
                },
                animation: false,
                tooltip: {
                    formatter: (params) => {
                        if (
                            params.seriesName !== "mouseoutSeries" &&
                            params.seriesName !== "pie2d"
                        ) {
                            return `${params.seriesName
                                }<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color
                                };"></span>占地面积${optionR.series[params.seriesIndex].pieData.value + "亩"
                                }`;
                        }
                    },
                    fontSize: 14,
                },
                title: {
                    x: "center",
                    top: "20",
                    color: "#fff",
                    fontSize: 22,
                },
                backgroundColor: "",
                labelLine: {
                    show: true,
                    lineStyle: {
                        length: 10,
                        length2: 10,
                        color: "#7BC0CB",
                    },
                },
                label: {
                    show: true,
                    formatter: function (param) {
                        return [`{a|${param.name}}` + '\n' + `{b|占地面积${param.value}亩}`];
                    },
                    rich: {
                        a: {
                            fontSize: 13,
                        },
                        b: {
                            fontSize: 14,
                        },
                    },
                },
                xAxis3D: {
                    min: -1,
                    max: 1,
                },
                yAxis3D: {
                    min: -1,
                    max: 1,
                },
                zAxis3D: {
                    min: -1,
                    max: 1,
                },
                grid3D: {
                    show: false,
                    boxHeight: 2,
                    top: '0%',
                    left: '4%',
                    bottom: "50%",
                    viewControl: {
                        distance: 250,
                        alpha: 40,
                        beta: 50,
                        autoRotate: false, // 自动旋转
                    },
                },
                series: series,
            };
            myChartR.setOption(optionR)
        },
        // 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
        getParametricEquation(
            startRatio,
            endRatio,
            isSelected,
            isHovered,
            k,
            height,
            i
        ) {
            // 计算
            let midRatio = (startRatio + endRatio) / 2;

            let startRadian = startRatio * Math.PI * 2;
            let endRadian = endRatio * Math.PI * 2;
            let midRadian = midRatio * Math.PI * 2;

            // 如果只有一个扇形，则不实现选中效果。
            if (startRatio === 0 && endRatio === 1) {
                isSelected = false;
            }

            // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
            k = typeof k !== "undefined" ? k : 1 / 3;

            // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
            let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
            let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;
            let offsetZ = i == 1 ? 2 : 0;
            // 计算高亮效果的放大比例（未高亮，则比例为 1）
            let hoverRate = isHovered ? 1.05 : 1;

            // 返回曲面参数方程
            return {
                u: {
                    min: -Math.PI,
                    max: Math.PI * 3,
                    step: Math.PI / 32,
                },

                v: {
                    min: 0,
                    max: Math.PI * 2,
                    step: Math.PI / 20,
                },

                x: function (u, v) {
                    if (u < startRadian) {
                        return (
                            offsetX +
                            Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
                        );
                    }
                    if (u > endRadian) {
                        return (
                            offsetX +
                            Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
                        );
                    }
                    return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
                },

                y: function (u, v) {
                    if (u < startRadian) {
                        return (
                            offsetY +
                            Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
                        );
                    }
                    if (u > endRadian) {
                        return (
                            offsetY +
                            Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
                        );
                    }
                    return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
                },

                z: function (u, v) {
                    if (u < -Math.PI * 0.5) {
                        return Math.sin(u);
                    }
                    if (u > Math.PI * 2.5) {
                        return Math.sin(u);
                    }
                    return Math.sin(v) > 0 ? 1 * height : -1;
                },
            };
        },
        // 生成模拟 3D 饼图的配置项
        getPie3D(pieData, internalDiameterRatio) {
            let series = [];
            let sumValue = 0;
            let startValue = 0;
            let endValue = 0;
            let legendData = [];
            let k =
                typeof internalDiameterRatio !== "undefined"
                    ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio)
                    : 1 / 3;

            // 为每一个饼图数据，生成一个 series-surface 配置
            for (let i = 0; i < pieData.length; i++) {
                sumValue += pieData[i].value;

                let seriesItem = {
                    name:
                        typeof pieData[i].name === "undefined"
                            ? `series${i}`
                            : pieData[i].name,
                    type: "surface",
                    parametric: true,
                    wireframe: {
                        show: false,
                    },
                    pieData: pieData[i],
                    pieStatus: {
                        selected: false,
                        hovered: false,
                        k: k,
                    },
                };

                if (typeof pieData[i].itemStyle != "undefined") {
                    let itemStyle = {};
                    typeof pieData[i].itemStyle.color != "undefined"
                        ? (itemStyle.color = pieData[i].itemStyle.color)
                        : null;
                    typeof pieData[i].itemStyle.opacity != "undefined"
                        ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
                        : null;

                    seriesItem.itemStyle = itemStyle;
                }
                series.push(seriesItem);
            }

            // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
            // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
            for (let i = 0; i < series.length; i++) {
                endValue = startValue + series[i].pieData.value;
                series[i].pieData.startRatio = startValue / sumValue;
                series[i].pieData.endRatio = endValue / sumValue;
                series[i].parametricEquation = this.getParametricEquation(
                    series[i].pieData.startRatio,
                    series[i].pieData.endRatio,
                    false,
                    false,
                    k,
                    // 调整扇形高度
                    i === 0 ? 10 : 10,
                    i,
                    series[i].pieData.value
                );

                startValue = endValue;

                legendData.push(series[i].name);
            }
            return series;
        },
    }
}
</script>
<style lang="less" scoped>
.plantBox {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    .title {
        font-size: 16px;
        font-weight: 400;
        color: #FFFFFF;
        line-height: 16px;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        display: flex;
        justify-content: space-between;
    }

    .plant-left {
        width: 49%;
        height: 98%;
    }

    .plant-right {
        width: 49%;
        height: 98%;
    }
}
</style>